import { isUnmarked } from './style_sheet_marker';
import { retryStyleSheet } from './style_sheet_retry';

export function eachStyleProperty(
  force: boolean,
  callback: (
    prop: string,
    styleObj: CSSStyleDeclaration,
    selectorText?: string
  ) => void
) {
  for (let i = 0; i < document.styleSheets.length; i++) {
    const styleSheet = document.styleSheets[i];
    if (styleSheet.cssRules && styleSheet.cssRules.length) {
      if (force || isUnmarked(styleSheet)) {
        eachStylePropertyRecursively(styleSheet.cssRules, callback);
      }
    } else {
      retryStyleSheet(styleSheet);
    }
  }
}

function eachStylePropertyRecursively(
  list: CSSRuleList,
  callback: (
    prop: string,
    styleObj: CSSStyleDeclaration,
    selectorText?: string
  ) => void
) {
  for (let i = 0; i < list.length; i++) {
    const rule = list[i];
    if (CSSRule.MEDIA_RULE === rule.type) {
      const mediaRule = rule as CSSMediaRule;
      eachStylePropertyRecursively(mediaRule.cssRules, callback);
    } else if (CSSRule.STYLE_RULE === rule.type) {
      const styleRule = rule as CSSStyleRule;
      const styleObj = styleRule.style;
      const selectorText = styleRule.selectorText;
      for (let j = 0; j < styleObj.length; j++) {
        const prop = styleObj[j];
        callback(prop, styleObj, selectorText);
      }
    }
  }
}
